package mil.af.amc.adpetracker.web.actions.struts1.Manufacturer.ajax;

import mil.af.amc.adpetracker.model.Manufacturer;
import mil.af.amc.adpetracker.service.ManufacturerService;
import mil.af.amc.adpetracker.web.actions.struts1.AbstractAction;
import net.sf.json.JSONArray;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

public class GetManufacturerByEquipmentTypeAction extends AbstractAction {

    Log log = LogFactory.getLog(GetManufacturerByEquipmentTypeAction.class);

    private ManufacturerService manufacturerService;

    public void setManufacturerService(ManufacturerService manufacturerService) {
        this.manufacturerService = manufacturerService;
    }

    @Override
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {

        int equipmentTypeId;
        if (request.getParameter("equipmentTypeId") == null) {
            equipmentTypeId = Integer.parseInt(request.getParameter("id"));
        } else {
            equipmentTypeId = Integer.parseInt(request.getParameter("equipmentTypeId"));
        }

        List<Manufacturer> manufacturerList = manufacturerService.getManufacturerByEquipmentType(equipmentTypeId);

        JSONArray jsonArray = JSONArray.fromObject(manufacturerList);

        response.setContentType("application/json");
        response.setHeader("Cache-Control", "no-cache");

        response.getWriter().println(jsonArray);

        request.getSession().setAttribute("equipmentTypeId", equipmentTypeId);

        return null;

    }
}
